import { mapGetters } from 'vuex'
import { exportTableColumns } from '@/bank/views/business/hplimit/enum'
import { excelJsonExport, columnToAbc } from '@vimi/utils-tool'
import { queryTrouble, service as axios } from '@vimi/utils-api'
export default {
  data() {
    return {
      exportLoading: false,
      tableName: 'datum_one_county_industry',
      order: {
        create_time: 'desc',
      },
      tableCount: 0,
    }
  },
  computed: {
    ...mapGetters(['userId', 'clientId', 'org', 'user']),
    isSubmit() {
      return this.user.scopes.includes('indoneBI')
    },
    isSYSTEM() {
      // 系统后台查所有
      return this.org.orgClass === 'org_credit_sys'
    },
    pages() {
      return Math.ceil(this.tableCount / 10000)
    },
    searchParamsSubmit() {
      const params = {}
      if (!this.isSYSTEM) {
        if (this.isSubmit) {
          params['submit_client_id.eq'] = this.clientId
        } else {
          params['orWhere.submit_person.eq'] = this.userId
          params['orWhere.res_a.eq'] = this.userId
          params['orWhere.res_b.eq'] = this.userId
        }
      }
      return params
    },
    searchParamsConfirm() {
      const params = {}
      if (!this.isSYSTEM) {
        if (this.isSubmit) {
          params['submit_client_id.eq'] = this.clientId
        } else {
          params['submit_person.eq'] = this.userId
        }
      }
      return params
    },
  },
  methods: {
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res = {}] = await this.fetchData(this.getParams())
      this.loading = false

      const data = res.data || {}
      this.tableCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.dataAdapter)
    },
    getParams() {
      return { ...this.params, ...this.searchParamsSubmit }
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData('credit', this.tableName, params, this.order || {})
      )
    },
    fetchDataTimeout(params) {
      params.fields = [
        'claim_bank_name',
        'address_name_city',
        'address_name_county',
        'customer_name',
        'org_class_name',
        'parent_main_business',
        'corp_name',
        'corp_phone',
        'is_cert_merge',
        'register_no',
        'lender_idcard',
        'warranty_amount',
        'load_date',
        'load_end_date',
        'warranty_period',
        'create_time',
        'use_category_name',
        'funds_use_dir',
        'gua_contract',
        'load_rate',
        'warranty_rate',
        'is_gua_fee_customer',
        'sale_income',
        'assets_total',
        'emp_total',
        'other_cost',
        'income_margin',
        'remark',
        'review_approval',
        'import_status',
        'ex_des',
        'reply_funds',
        'load_date_credit',
        'load_end_date_credit',
        'period_credit',
      ]
      return axios
        .get(
          `/api/credit/${this.tableName}${queryTrouble(this.tableName, params, this.order || {})}`,
          {
            timeout: 0,
          }
        )
        .then(res => res?.data?.data ?? [])
    },
    async exportExcel(filename, exportData) {
      const exportTable = exportTableColumns.filter(item => !item.operations && !item.hidden)
      const header = {}

      if (this.tableName === 'un_gua_record_view') {
        exportTable.push({ attrs: { label: '解保状态', prop: 'postloanStatus' } })
        exportTable.push({ attrs: { label: '解保金额（万元）', prop: 'un_gua_funds' } })
        exportTable.push({ attrs: { label: '解保日期', prop: 'unGuaDate' } })
      }
      const headerCellStyles = {}
      const columns = exportTable.map((item, i) => {
        const { prop, label } = item.attrs || {}
        header[prop] = label
        headerCellStyles[`${columnToAbc(i)}3`] = { font: { bold: true } }
        // headerCellStyles[`${columnToAbc(i)}2`] = { font: { bold: true } }
        return prop
      })
      let data = []
      if (exportData) {
        data = exportData.map((item, index) => {
          return {
            index: index + 1,
            ...this.dataAdapter(item),
          }
        })
      } else {
        this.exportLoading = true
        const { index, size, subKey, ...params } = this.params
        const [res = {}] = await this.fetchData(params)

        data = (res.data || []).map((item, index) => {
          return {
            index: index + 1,
            ...this.dataAdapter(item),
          }
        })
      }
      const title1 = {
        index: '普惠贷',
      }
      excelJsonExport({
        columns,
        data: [title1, title1, title1, header, ...data],
        filename,
        styles: {
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        merges: ['A1:AE3'],
        cols: [{ wch: 6 }],
        cellStyles: {
          A1: {
            alignment: { horizontal: 'left' },
            font: { bold: true, sz: 24 },
          },
          A2: { alignment: { horizontal: 'left' }, font: { bold: true } },
          ...headerCellStyles,
        },
      }).finally(() => {
        this.exportLoading = false
      })
    },
  },
}
